package MemberController;

import javax.servlet.http.*;
import java.util.*;

public class MLoginManager implements HttpSessionBindingListener {

	private static MLoginManager loginManager = null;
	private static Hashtable loginUsers = new Hashtable();
	private static MembersDAO mdao = new MembersDAO();
	
	public MLoginManager() {
		
		super();
	}
	
	public static synchronized MLoginManager getInstance() {
		
		if ( loginManager == null ) {
			
			loginManager = new MLoginManager();
		}
		return loginManager;
	}
	
	
	
	//해당 세션에 이미 로그인 되었는지 체크!
	public boolean isLogin( String sessionID ) {
		
		boolean isLogin = false;
		
		Enumeration e = loginUsers.keys();
		HttpSession session = null;
		
		while ( e.hasMoreElements() ) {
			
			session = ( HttpSession ) e.nextElement();
			
			if ( sessionID.equals( session.getId() ) ) {
				
				isLogin = true;
			}
		}
		
		return isLogin;
	}
	
	//이미 접속되어서 사용되고 있는 아이디인지 체크!
	public boolean isUsing( String userID ) {
		
		boolean isUsing = false;
		
		Enumeration e = loginUsers.keys();
		HttpSession session=null;
		
		while ( e.hasMoreElements() ) {
			
			session = (HttpSession) e.nextElement();
			
			if ( userID.equals( loginUsers.get( session ) ) ) {
				
				isUsing = true;
			}
		}
		return isUsing;
	}
	//New 세션 생성!
	public void setSession( HttpSession session, MembersBean mbean ) {//새로운 세션을 등록합니다.
		
		loginUsers.put( session,mbean.getMem_Nick() );
		
		session.setAttribute( "login",this.getInstance() );
	}
	//세션 성립될 때!
	public void valueBound( HttpSessionBindingEvent event ) {
		
	}
	//세션 끊길때!
	public void valueUnbound( HttpSessionBindingEvent event ) {
		
			loginUsers.remove( event.getSession() );
	}
	//세션을 삭제합니다.
	public void removeSession( String userId ) {
		
		Enumeration e = loginUsers.keys();        
        HttpSession session=null;
        
        while ( e.hasMoreElements() ) {
        	
        	session = ( HttpSession ) e.nextElement();
        	
        	if ( loginUsers.get( session ).equals( userId) ) {
        		
        		loginUsers.remove( loginUsers.get( session ) );
        		session.invalidate();
        	}
        }
	}
	//세션 ID로 로긴된 ID구분
	public String getUserID( HttpSession session ) {
		
		return (String) loginUsers.get( session );
	}
	//현재 접속자 수
	public int getUserCount() {
		
		return loginUsers.size();
	}
	
}
